package cz.data.domain.metadata.controller;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import cz.data.common.base.BaseController;
import cz.data.common.base.BaseResponse;
import cz.data.common.base.SimpleDataResponse;
import cz.data.common.core.JsonPage;
import cz.data.common.exception.DataException;
import cz.data.common.validate.ValidationGroups;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cz.data.domain.metadata.mapstruct.MetadataTableMapper;
import cz.data.domain.metadata.model.dto.MetadataTableDto;
import cz.data.domain.metadata.model.entity.MetadataTableEntity;
import cz.data.domain.metadata.model.query.MetadataTableQuery;
import cz.data.domain.metadata.model.vo.MetadataTableVo;
import cz.data.domain.metadata.service.MetadataTableService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

@Api(tags = {"元数据表"})
@RestController
@RequestMapping("/tables")
public class MetadataTableController extends BaseController {

    @Autowired
    private MetadataTableService metadataTableService;
    @Autowired
    private MetadataTableMapper metadataTableMapper;

    @ApiOperation(value = "元数据表-详情", notes = "根据url的id来获取详细信息")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String", paramType = "path")
    @GetMapping("/{id}")
    public SimpleDataResponse<MetadataTableVo> getDataMetadataTableById(@PathVariable String id) {
        MetadataTableEntity metadataTableEntity = metadataTableService.getMetadataTableById(id);
        return new SimpleDataResponse<>(metadataTableMapper.toVO(metadataTableEntity));
    }

    @ApiOperation(value = "元数据表-列表")
    @GetMapping("/list")
    public SimpleDataResponse<List<MetadataTableVo>> getDataMetadataTableList(MetadataTableQuery metadataTableQuery) {
        List<MetadataTableEntity> list = metadataTableService.getDataMetadataTableList(metadataTableQuery);
        List<MetadataTableVo> collect = list.stream().map(metadataTableMapper::toVO).collect(Collectors.toList());
        return new SimpleDataResponse<>(collect);
    }

    @GetMapping("/source/{id}")
    public List<MetadataTableEntity> getMetadataTableBySourceId(@PathVariable("id") String id) {
        return metadataTableService.getDataMetadataTableList(MetadataTableQuery.formSourceId(id));
    }

    @ApiOperation(value = "元数据表-分页查询")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dataMetadataTableQuery", value = "查询实体dataMetadataTableQuery", required = true, dataTypeClass = MetadataTableQuery.class)
    })
    @GetMapping("/page")
    public SimpleDataResponse<JsonPage<MetadataTableVo>> getDataMetadataTablePage(MetadataTableQuery metadataTableQuery) {
        QueryWrapper<MetadataTableEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(metadataTableQuery.getTableName()), "t.table_name", metadataTableQuery.getTableName());
        queryWrapper.eq(StringUtils.isNotBlank(metadataTableQuery.getSourceId()), "t.source_id", metadataTableQuery.getSourceId());
        IPage<MetadataTableEntity> page = metadataTableService.pageWithAuth(new Page<>(metadataTableQuery.getPageNum(), metadataTableQuery.getPageSize()), queryWrapper);
        List<MetadataTableVo> collect = page.getRecords().stream().map(metadataTableMapper::toVO).collect(Collectors.toList());
        JsonPage<MetadataTableVo> jsonPage = new JsonPage<>(page.getCurrent(), page.getSize(), page.getTotal(), collect);
        return new SimpleDataResponse<>(jsonPage);
    }

    @ApiOperation(value = "元数据表-添加", notes = "根据dataMetadataTable对象添加信息")
    @ApiImplicitParam(name = "dataMetadataTable", value = "详细实体dataMetadataTable", required = true, dataType = "DataMetadataTableDto")
    @PostMapping()
    public SimpleDataResponse<MetadataTableVo> saveDataMetadataTable(@RequestBody @Validated({ValidationGroups.Insert.class}) MetadataTableDto dataMetadataTable) {
        MetadataTableEntity tableEntity = metadataTableService.saveMetadataTable(dataMetadataTable);
        return new SimpleDataResponse<>(metadataTableMapper.toVO(tableEntity));
    }

    @ApiOperation(value = "元数据表-修改", notes = "根据url的id来指定修改对象，并根据传过来的信息来修改详细信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "dataMetadataTable", value = "详细实体dataMetadataTable", required = true, dataType = "DataMetadataTableDto")
    })
    @PutMapping
    public SimpleDataResponse<MetadataTableVo> updateDataMetadataTable(@RequestBody @Validated({ValidationGroups.Update.class}) MetadataTableDto dataMetadataTable) {
        MetadataTableEntity metadataTableEntity = metadataTableService.updateMetadataTable(dataMetadataTable);
        return new SimpleDataResponse<>(metadataTableMapper.toVO(metadataTableEntity));
    }

    @ApiOperation(value = "元数据表-修正")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "表ID", required = true, dataType = "String"),
            @ApiImplicitParam(name = "tableComment", value = "表注释", required = true, dataType = "String")
    })
    @PutMapping("/amend")
    public BaseResponse amendTable(@RequestBody @Validated({ValidationGroups.Update.class}) MetadataTableDto request) {
        String id = request.getId();
        String tableComment = request.getTableComment();
        if (StringUtils.isBlank(tableComment)) {
            throw new DataException("参数: tableComment(表注释)不能为空");
        }
        UpdateWrapper<MetadataTableEntity> update = new UpdateWrapper<>();
        update.lambda().eq(MetadataTableEntity::getId, id);
        update.lambda().set(MetadataTableEntity::getTableComment, tableComment);
        return BaseResponse.withBoolean(metadataTableService.update(update));
    }

    @ApiOperation(value = "元数据表-删除", notes = "根据url的id来指定删除对象")
    @ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "String", paramType = "path")
    @DeleteMapping("/{id}")
    public BaseResponse deleteDataMetadataTableById(@PathVariable String id) {
        metadataTableService.deleteMetadataTableById(id);
        return BaseResponse.success();
    }

    @ApiOperation(value = "元数据表-批量删除", notes = "根据url的ids来批量删除对象")
    @ApiImplicitParam(name = "ids", value = "ID集合", required = true, dataType = "List", paramType = "path")
    @DeleteMapping("/batch/{ids}")
    public BaseResponse deleteDataMetadataTableBatch(@PathVariable List<String> ids) {
        metadataTableService.deleteMetadataTableBatch(ids);
        return BaseResponse.success();
    }
}
